package fda.base;

import java.util.List;

import fda.schema.Column;
import fda.schema.TableInfo;

/**
 * Structure represent a record of data.
 */
public class Tuple {

	private static final long DEFAULT_KEY = -1;

	private final String recordLine;
	private long keyValue = DEFAULT_KEY;
	private final TableInfo tableInfo;

	public Tuple(String line, TableInfo info) {
		this.tableInfo = info;
		recordLine = line;
		//id = readId(line);
	}

	/**
	 * @return line of data (original line)
	 */
	public String getLine() {
		return recordLine;
	}

	/**
	 * @return key of current tuple, first number in line: ID: int(7)
	 */
	public long getKeyValue() {
		if (keyValue == DEFAULT_KEY) {
			keyValue = readKeyValue();
		}
		return keyValue;
	}
	
	/**
	 * @return length of primary key column
	 */
	public int getKeyLength() {
		return tableInfo.getCols().get(tableInfo.getPrimeKeyIndex()).length;
	}

	/**
	 * @return name of column for primary Key
	 */
	public String getKeyColumnName() {
		int keyIndex = tableInfo.getPrimeKeyIndex();
		return tableInfo.getCols().get(keyIndex).name;
	}

	/**
	 * @param colName name of column
	 * @return value of column with name <b>colName</b>
	 */
	public String getValue(String colName) {
		int index = -1;
		for (Column c : tableInfo.getCols()) {
			++index;
			if (c.name.equalsIgnoreCase(colName))
				return valueOf(index);
		}

		throw new IllegalStateException("Cannot find column: " + colName);
	}

	/**
	 * @param columnNumber column to find value for
	 * @return String representation of value for column
	 */
	public String valueOf(int columnNumber) {
		int offset = 0;
		List<Column> cols = tableInfo.getCols();

		for (int i = 0; i < columnNumber; ++i) {
			offset += cols.get(i).length;
		}
		int lastIndex = Math.min(offset + cols.get(columnNumber).length, recordLine.length());
		return recordLine.substring(offset, lastIndex);
	}

	private long readKeyValue() {
		try {
			return Long.parseLong(valueOf(tableInfo.getPrimeKeyIndex()).trim());
		}
		catch (Exception ex) {
			System.out.print(String.format("\nERROR : cannot parse %s \n %s\n\n",
					valueOf(tableInfo.getPrimeKeyIndex()), ex.getMessage()));
		}

		return DEFAULT_KEY;
	}

	public TableInfo getTableInfo() {
		return tableInfo;
	}
}
